package com.hundsun.cprs.yyt.util;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.hundsun.cprs.yyt.common.redis.RedisCounterFactory;

@Component
public class SequenceUtils implements ApplicationContextAware{
    
    public static final String BIZ_ORDER = "10";
	public static final String BIZ_RETURN = "50";

	//本机IP的最后一个字节作为标识
	private static final String machiceId =  String.valueOf((0x000000FF & getLastIP()));
	
	private static final String data_format_SSS = "yyyyMMddHHmmssSSS";
	
	private static final String simple_data_format_SSS = "yyMMddHHmmssSSS";
	
	private static final String data_format = "yyyyMMddHHmmss";
	
	private static RedisCounterFactory counter;
	
	private static byte getLastIP(){
		byte lastip = 0;
        try{
            InetAddress ip = InetAddress.getLocalHost();
            byte[] ipByte = ip.getAddress();
            lastip = ipByte[ipByte.length - 1];
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return lastip;
	}
	
	public static String generateSequenceByUUID(){
		int hashCodeV = UUID.randomUUID().toString().hashCode();
		if(hashCodeV < 0) {//有可能是负数  
			 hashCodeV = - hashCodeV;  
		}  
		return String.format("%012d", hashCodeV); 
	}
	
	/**
	 * 简单的时间戳+UUID.hashcode 序列号
	 * @return
	 */
	public static String getSequenceWithTimestamp(){
		return DateFormatUtils.format(System.currentTimeMillis(), data_format_SSS) + generateSequenceByUUID();
	}
	
	public static String generateSequence(String biz){
	    return new StringBuffer(biz)
	            .append(DateFormatUtils.format(System.currentTimeMillis(), simple_data_format_SSS))
	            //.append(String.format("%03d", counter.generate("SN:COUNTER:"+biz, 10000, TimeUnit.MILLISECONDS)))
	            .append(String.format("%03d", counter.circleSequence("SN:COUNTER",999)))
	            .toString();
	}
	
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SequenceUtils.counter = applicationContext.getBean(RedisCounterFactory.class);
    }
    
}
